using BlazorAdmin.Models;
using BlazorAdmin.Interface;
using BootstrapBlazor.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BlazorAdmin.Services.DbService;

namespace BlazorAdmin.Services
{
    /// <summary>
    /// Organize 服务
    /// </summary>
    public class OrganizeService : BaMgmtDbService, IOrganize
    {
        public OrganizeService(IPetaPoco db) : base(db) { }

        /// <summary>
        /// 保存、更新
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>错误消息</returns>
        public Task<string> Save(Organize entity)
        {
            using var db = Create();
            bool isUpdate = entity.ID > 0;

            try
            {
                if (isUpdate)
                    db.Update(entity);
                else
                    db.Insert(entity);
            }
            catch (Exception ex)
            {

                return Task.FromResult($"保存出错，{ex.Message}");
            }

            return Task.FromResult(string.Empty);
        }

        /// <summary>
        /// 递归删除组织
        /// </summary>
        /// <param name="orgCode">组织代码</param>
        /// <returns>错误消息</returns>
        public Task<string> Delete(string orgCode)
        { 
            try
            {
                // 调用函数递归删除子节点
                var effectRows = Create().FirstOrDefault<int>("SELECT Sys.RemoveOrganizes(@0)", orgCode);

                if (effectRows > 0)
                    return Task.FromResult(string.Empty);
                else
                    return Task.FromResult("删除失败，受影响的行数为0");
            }
            catch (Exception ex)
            {
                return Task.FromResult(ex.Message);
            }
        }

        private string GetAuthSql(string usrOrgCode)
        {
            return $@"and OrgCode in (
                        with recursive subtree(org_code, parent_orgcode) as (
		                    select OrgCode, ParentOrgCode from Organizes where OrgCode = '{usrOrgCode}'
                            union all
                            select OrgCode, ParentOrgCode from Organizes
                            join subtree on ParentOrgCode = subtree.org_code
	                    ), fathertree(org_code, parent_orgcode) as (
                            select OrgCode, ParentOrgCode from Organizes where OrgCode = '{usrOrgCode}'
                            union all
                            select OrgCode, ParentOrgCode from Organizes
                            join fathertree on OrgCode = fathertree.parent_orgcode
	                    )
	                    select org_code from subtree
                        union
                        select org_code from fathertree
                      )";
        }

        public Task<List<TreeViewItem<Organize>>> GetOrganizeTree(string curUser, bool isChoose)
        {
            using var db = Create();
            var tree = new List<TreeViewItem<Organize>>();
            var strSql = "Select * From Organizes Where IsEnable = 'True'";

            if(curUser != SysConsts.Admin) // 非管理员根据组织权限设置
            {
                var usrOrgCode = db.FirstOrDefault<string>($"select OrgCode from UserOrganize where UserName = '{curUser}'");
                if (!string.IsNullOrEmpty(usrOrgCode))
                    strSql += GetAuthSql(usrOrgCode);
                else // 无权限则没有数据
                    return Task.FromResult(tree);
            }
            strSql += " Order By Sort";

            var organizes = db.Query<Organize>(strSql).ToList();

            var defaultOrg = organizes.FirstOrDefault(t => t.OrgCode.ToLower() == "default");
            if (defaultOrg == null) // 不存在未分组，则创建
            {
                defaultOrg = new Organize() { 
                    OrgCode = "Default", 
                    OrgName = "系统默认", 
                    OrgIcon = "fas fa-circle-question",
                    ModifyUser = "System",
                    ModifyTime = DateTime.Now,
                    IsEnable = true,
                };

                db.Insert(defaultOrg);
            }

            if (!isChoose)
                tree.Add(new TreeViewItem<Organize>(defaultOrg) { Text = defaultOrg.OrgName, Icon = defaultOrg.OrgIcon, IsExpand = true });

            foreach (var org in organizes)
            {
                if (string.IsNullOrWhiteSpace(org.ParentOrgCode) && org.OrgCode.ToLower() != "default") // 先创建所有根节点
                {
                    var item = new TreeViewItem<Organize>(org)
                    {
                        Text = org.OrgName,
                        Icon = org.OrgIcon,
                        IsExpand = true
                    };
                    tree.Add(item);

                    RecurseCreateChildren(isChoose, organizes, item);
                }
            }

            return Task.FromResult(tree);
        }

        /// <summary>
        /// 遍历创建子节点
        /// </summary>
        private void RecurseCreateChildren(bool isSelect, List<Organize> groups, TreeViewItem<Organize> parentItem)
        {
            foreach (var group in groups)
            {
                if (group.ParentOrgCode == parentItem.Value.OrgCode)
                {
                    var item = new TreeViewItem<Organize>(group)
                    {
                        Text = group.OrgName,
                        Icon = group.OrgIcon,
                        Parent = parentItem
                    };
                    parentItem.HasChildren = true;
                    parentItem.Items.Add(item);

                    RecurseCreateChildren(isSelect, groups, item);
                }
            }
        }
    }
}
